﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.RoleManage
{
    /// <summary>
    /// RoleManage 的摘要说明
    /// </summary>
    public class RoleManage : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "Role": LoadRoleList(); break; //角色列表
            }
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        private void LoadRoleList()
        {
            int count = 0;
            int pageSize = con.Request["rows"].ToInt32(15);
            int curPage = con.Request["page"].ToInt32(1);

            IList<SqlParam> IList_param = new List<SqlParam>();
            StringBuilder SqlWhere = new StringBuilder(WebHelper.GetCondition(con.Request));
            SqlWhere.AppendFormat(" AND IsDelete=0");

            string tables = @" SYS_Roles ";
            string cols = @" * ";
            string orderStr = " Sort Asc ";

            DataTable dt = systemidao.GetListByPage(tables, cols, SqlWhere, orderStr, IList_param, curPage, pageSize, ref count);

            json.success = true;
            json.total = count;
            json.rows = dt;

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Role": GetRole(); break; //获取角色
            }
        }

        /// <summary>
        /// 获取角色
        /// </summary>
        private void GetRole()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("SYS_Roles", "GUID", guid);

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Role": SetRole(); break; //角色保存
                case "RoleRight": SetRoleRight(); break; //分配角色权限
                case "UserRight": SetUserRight(); break; //分配用户权限
            }
        }

        /// <summary>
        /// 角色保存
        /// </summary>
        private void SetRole()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();
                string roleName = con.Request["RoleName"].ToString2();

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT GUID FROM dbo.SYS_Roles WHERE IsDelete=0 AND RoleName='{roleName}' AND GUID!='{guid}'"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    json.msg = "角色名称已存在！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                Hashtable ht = systemidao.AddHashtable("SYS_Roles", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                bool result = systemidao.SubmitData("SYS_Roles", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 分配角色权限
        /// </summary>
        private void SetRoleRight()
        {
            string rightItems = con.Request["RightItems"];
            string roleGUID = con.Request["RoleGUID"];
            string[] item_value = rightItems.Split(',');
            StringBuilder[] sqls = new StringBuilder[item_value.Length + 4];
            object[] objs = new object[item_value.Length + 4];
            StringBuilder sbDelete_Right = new StringBuilder();
            sbDelete_Right.Append("DELETE SYS_RoleRight WHERE RoleGUID=@RoleGUID");
            SqlParam[] parm_Right = new SqlParam[]
            {
                new SqlParam("@RoleGUID", roleGUID)
            };
            sqls[0] = sbDelete_Right;
            objs[0] = parm_Right;
            int index = 1;
            for (int i = 0; i < item_value.Length; i++)
            {
                string item = item_value[i];
                if (item.Length > 0)
                {
                    StringBuilder sbadd = new StringBuilder();
                    sbadd.Append(@"INSERT INTO dbo.SYS_RoleRight (GUID,RoleGUID,MenuGUID,CreateDate)
                    VALUES (@GUID,@RoleGUID,@MenuGUID,@CreateDate)");
                    SqlParam[] parmAdd = new SqlParam[]
                    {
                        new SqlParam("@GUID", CommonHelper.GetGuid),
                        new SqlParam("@RoleGUID", roleGUID),
                        new SqlParam("@MenuGUID", item),
                        new SqlParam("@CreateDate", DateTime.Now)
                    };
                    sqls[index] = sbadd;
                    objs[index] = parmAdd;
                }
                index++;
            }
            bool returnValue = systemidao.BatchExecuteBySql(sqls, objs) >= 0;
            json.success = returnValue;
            if (returnValue)
            {
                json.msg = "保存成功！";
            }
            else
            {
                json.msg = "保存失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 分配用户权限
        /// </summary>
        private void SetUserRight()
        {
            string rightItems = con.Request["RightItems"];
            string userGUID = con.Request["UserGUID"];
            string[] item_value = rightItems.Split(',');
            StringBuilder[] sqls = new StringBuilder[item_value.Length + 4];
            object[] objs = new object[item_value.Length + 4];
            StringBuilder sbDelete_Right = new StringBuilder();
            sbDelete_Right.Append("DELETE dbo.SYS_UserRight WHERE UserGUID=@UserGUID");
            SqlParam[] parm_Right = new SqlParam[]
            {
                new SqlParam("@UserGUID", userGUID)
            };
            sqls[0] = sbDelete_Right;
            objs[0] = parm_Right;
            int index = 1;
            for (int i = 0; i < item_value.Length; i++)
            {
                string item = item_value[i];
                if (item.Length > 0)
                {
                    StringBuilder sbadd = new StringBuilder();
                    sbadd.Append(@"INSERT INTO dbo.SYS_UserRight (GUID,UserGUID,MenuGUID,CreateDate)
                    VALUES (@GUID,@UserGUID,@MenuGUID,@CreateDate)");
                    SqlParam[] parmAdd = new SqlParam[]
                    {
                        new SqlParam("@GUID", CommonHelper.GetGuid),
                        new SqlParam("@UserGUID", userGUID),
                        new SqlParam("@MenuGUID", item),
                        new SqlParam("@CreateDate", DateTime.Now)
                    };
                    sqls[index] = sbadd;
                    objs[index] = parmAdd;
                }
                index++;
            }
            bool returnValue = systemidao.BatchExecuteBySql(sqls, objs) >= 0;
            json.success = returnValue;
            if (returnValue)
            {
                json.msg = "保存成功！";
            }
            else
            {
                json.msg = "保存失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "Role": DelRole(); break; //角色删除
            }
        }

        /// <summary>
        /// 角色删除
        /// </summary>
        private void DelRole()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("SYS_Roles", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}